
//
//  TBUserAccount.swift
//  新浪微博
//
//  Created by bin on 16/1/27.
//  Copyright © 2016年 XMG. All rights reserved.
//

import UIKit



class TBUserAccount: NSObject,NSCoding {
    /**
    *      
    "access_token" = "2.00zkVobCGHSkMB7e6979d99cm2WbGD";
    "expires_in" = 157679999;
    "remind_in" = 157679999;
    uid = 2391028573;
    */
    static let filePath = "userAccount.plist".cachePath()
    static var userAccount:TBUserAccount?
    var profile_image_url: String?
    var screen_name: String?
    var access_token: String?
    var expires_in: NSNumber?{
        didSet{
//            expires_in = 1
            expires_Date = NSDate(timeIntervalSinceNow: (expires_in?.doubleValue)!)
        }
    }
    var uid: String?
    var expires_Date: NSDate?
    
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String{
        let keys = ["access_token" , "expires_in" , "uid","expires_Date"]
        let dict = dictionaryWithValuesForKeys(keys)
        return "\(dict)"
    }

    func archiveToFile(){
        
        NSKeyedArchiver.archiveRootObject(self, toFile: TBUserAccount.filePath)
    }
    
    class func loadFormFile() -> TBUserAccount?{

        
        if nil == userAccount{
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(TBUserAccount.filePath) as? TBUserAccount
//            print("loadFormFile")
            return userAccount
        }
        return userAccount
        
    }
    
    class func isLogin() -> Bool{
       
        if  let userAccount = TBUserAccount.loadFormFile() where userAccount.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending  {
            return true
        }
        return false
    }
    
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(profile_image_url, forKey: "profile_image_url")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
    }
    
    required init?(coder aDecoder: NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        profile_image_url = aDecoder.decodeObjectForKey("profile_image_url") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
    }
    

}


